package cn.itsource.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LogInterceptor implements HandlerInterceptor{

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取请求头中TOKEN
        String token = request.getHeader("TOKEN");
        // 获取redis中token值
        Object o = redisTemplate.opsForValue().get(token);
        if(o!=null){// 判断有没有token，有的话就代表登陆过，放行
            // 存设置redis刷新有效期30分钟
            redisTemplate.opsForValue().set(token,o,30, TimeUnit.MINUTES);
            return true;
        }
        // 设置响应头和编码
        response.setContentType("application/json;charset=utf-8");

        PrintWriter writer = response.getWriter();
        //("success":false,"message":""noAuth)
         writer.print("\"success\":false,\"message\":\"\"noAuth");

        return false;
    }
}
